package edu.jinghuan.lms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.jinghuan.lms.entity.Book;
import edu.jinghuan.lms.entity.Borrow;
import edu.jinghuan.lms.entity.OverdueConfig;
import edu.jinghuan.lms.entity.dto.BorrowWithRemainingDaysDTO;
import edu.jinghuan.lms.mapper.BorrowMapper;
import edu.jinghuan.lms.service.IBookService;
import edu.jinghuan.lms.service.IBorrowService;
import edu.jinghuan.lms.service.OverdueConfigService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class BorrowServiceImpl extends ServiceImpl<BorrowMapper, Borrow> implements IBorrowService {
    
    private final IBookService bookService;
    
    @Autowired
    private OverdueConfigService overdueConfigService;

    @Override
    @Transactional
    public boolean save(Borrow borrow) {
        // 检查图书是否存在且可借
        Book book = bookService.getById(borrow.getBookId());
        if (book == null || book.getAvailableCount() <= 0) {
            return false;
        }

        // 更新图书可借数量
        book.setAvailableCount(book.getAvailableCount() - 1);
        bookService.updateById(book);

        // 保存借阅记录
        borrow.setStatus("BORROWED");
        return super.save(borrow);
    }

    @Override
    @Transactional
    public boolean updateById(Borrow borrow) {
        Borrow oldBorrow = getById(borrow.getId());
        if (oldBorrow == null) {
            return false;
        }

        // 如果是归还操作
        if ("RETURNED".equals(borrow.getStatus()) && !"RETURNED".equals(oldBorrow.getStatus())) {
            Book book = bookService.getById(oldBorrow.getBookId());
            if (book != null) {
                book.setAvailableCount(book.getAvailableCount() + 1);
                bookService.updateById(book);
            }
        }

        return super.updateById(borrow);
    }

    @Override
    public Page<BorrowWithRemainingDaysDTO> pageWithRemainingDays(Page<Borrow> page, LambdaQueryWrapper<Borrow> queryWrapper) {
        // 获取原始分页数据
        Page<Borrow> borrowPage = page(page, queryWrapper);
        
        // 获取超期配置
        OverdueConfig config = overdueConfigService.getCurrentConfig();
        int overdueDays = config != null ? config.getDays() : 30; // 默认30天
        
        // 转换为带有剩余天数的DTO
        List<BorrowWithRemainingDaysDTO> records = borrowPage.getRecords().stream()
                .map(borrow -> {
                    BorrowWithRemainingDaysDTO dto = new BorrowWithRemainingDaysDTO();
                    BeanUtils.copyProperties(borrow, dto);
                    
                    // 计算剩余天数
                    LocalDateTime borrowTime = borrow.getCreateTime();
                    LocalDateTime now = LocalDateTime.now();
                    long daysPassed = ChronoUnit.DAYS.between(borrowTime, now);
                    dto.setRemainingDays((int) (overdueDays - daysPassed));
                    
                    return dto;
                })
                .collect(Collectors.toList());
        
        // 创建新的分页对象
        Page<BorrowWithRemainingDaysDTO> dtoPage = new Page<>(
                borrowPage.getCurrent(),
                borrowPage.getSize(),
                borrowPage.getTotal()
        );
        dtoPage.setRecords(records);
        
        return dtoPage;
    }
}
